/**
 * 文件名称: comboQuery_report.js
 * 完整存储路径: frontend/static/js/comboQuery_report.js
 *
 * 功能说明:
 *   此模块为统计报表页面专用的组合查询功能实现。
 *   主要功能包括：
 *     1. 动态添加查询条件行，支持多种控件：
 *          - "text": 文本输入框
 *          - "number_range": 数值区间查询（生成最小值和最大值两个输入框）
 *          - "multi-select": 生成复选框组，每个选项前添加复选框
 *          - "checkbox": 生成单个复选框
 *     2. 🔧 配置驱动：从后端API动态加载字段配置，支持角色化配置
 *          - 统计指标字段：用于统计计算的字段
 *          - 分组字段：用于数据分组的字段  
 *          - 筛选字段：用于数据过滤的字段
 *     3. 每个查询条件行中新增角色选择下拉框（占2列），用于指定该条件的角色：
 *          - 角色选项包括："metric"（统计指标）、"group"（分组）、"filter"（筛选）
 *     4. 提供 getitions() 函数，遍历所有条件行，返回 JSON 数组，每个条件对象包含：
 *          { role: <角色>, field: <字段名>, operator: <运算符>, value: <查询值> }
 *     5. 提供 clearConditions() 函数，清除所有查询条件行。
 *
 * 使用说明:
 *   在统计报表页面 (report.html) 中，必须包含：
 *     - 条件容器 (id="advancedQueryContainer") 用于插入查询条件行
 *     - 隐藏输入框 (id="comboConditions") 用于存储查询条件 JSON 字符串
 *     - "添加条件"按钮 (id="addConditionBtn") 和 "清除条件"按钮 (id="clearConditionsBtn")
 *
 * 注意:
 *   修改过程中必须保证不破坏原有功能，并且所有代码均符合我们的代码编写与输出标准。
 */

// 🔧 配置驱动：动态加载的字段配置
let comboQueryConfig = {};
let roleOptions = [];

// 🔧 配置驱动：从后端API动态加载配置
async function loadComboQueryConfig() {
  try {
    // 加载角色化字段配置
    const roleConfigResponse = await fetch('/api/config/report-role-field-config');
    const roleConfigData = await roleConfigResponse.json();
    
    if (roleConfigData.success && roleConfigData.data) {
      comboQueryConfig = roleConfigData.data;
    } else {
      console.error("获取角色化字段配置失败");
      throw new Error("配置加载失败");
    }
    
    // 加载角色选项配置
    const roleOptionsResponse = await fetch('/api/config/report-role-options');
    const roleOptionsData = await roleOptionsResponse.json();
    
    if (roleOptionsData.success && roleOptionsData.data) {
      roleOptions = roleOptionsData.data;
    } else {
      console.error("获取角色选项配置失败");
      throw new Error("角色配置加载失败");
    }
    
    console.log("✅ 组合查询配置加载成功:", {
      metric_fields: Object.keys(comboQueryConfig.metric_fields || {}).length,
      group_fields: Object.keys(comboQueryConfig.group_fields || {}).length,
      filter_fields: Object.keys(comboQueryConfig.filter_fields || {}).length,
      roles: roleOptions.length
    });
    
    // 🔧 调试：打印详细配置信息
    console.log("📊 详细配置信息:", {
      metric_fields: comboQueryConfig.metric_fields,
      group_fields: comboQueryConfig.group_fields,
      filter_fields: comboQueryConfig.filter_fields,
      role_options: roleOptions
    });
    
  } catch (error) {
    console.error("加载组合查询配置失败:", error);
    throw error; // 不进行降级处理，让错误向上传播
  }
}

// 🔧 获取字段选项（统一从后端获取）
async function getFieldOptions(fieldName) {
  try {
    console.log(`🔍 正在获取字段 ${fieldName} 的选项...`);
    const response = await fetch(`/api/config/report-field-options/${fieldName}`);
    const data = await response.json();
    console.log(`📊 字段 ${fieldName} 的响应数据:`, data);
    
    if (data.success && data.data && Array.isArray(data.data)) {
      console.log(`✅ 字段 ${fieldName} 获取到 ${data.data.length} 个选项:`, data.data);
      return data.data;
    } else {
      console.warn(`❌ 字段 ${fieldName} 选项数据无效:`, data);
      return [];
    }
  } catch (error) {
    console.error(`❌ 获取字段${fieldName}选项失败:`, error);
    return [];
  }
}

// 🔧 获取字段显示名称（从全局配置获取）
async function getFieldDisplayName(fieldName) {
  try {
    const response = await fetch(`/api/config/report-field-info/${fieldName}`);
    const data = await response.json();
    if (data.success && data.data && data.data.display_name) {
      return data.data.display_name;
    }
  } catch (error) {
    console.warn(`获取字段${fieldName}显示名称失败:`, error);
  }
  
  // 降级处理：返回字段名
  return fieldName;
}

// 🔧 获取角色字段配置（包含显示名称）
async function getRoleFieldsWithDisplayNames(role) {
  let roleFields = {};
  let fieldOrder = [];
  if (role === "metric") {
    roleFields = comboQueryConfig.metric_fields || {};
    fieldOrder = comboQueryConfig.metric_field_order || Object.keys(roleFields);
  } else if (role === "group") {
    roleFields = comboQueryConfig.group_fields || {};
    fieldOrder = comboQueryConfig.group_field_order || Object.keys(roleFields);
  } else if (role === "filter") {
    roleFields = comboQueryConfig.filter_fields || {};
    fieldOrder = comboQueryConfig.filter_field_order || Object.keys(roleFields);
  }
  // 为每个字段添加显示名称，严格按顺序数组遍历
  const fieldsWithDisplayNames = {};
  for (const fieldName of fieldOrder) {
    const fieldConfig = roleFields[fieldName];
    const displayName = await getFieldDisplayName(fieldName);
    fieldsWithDisplayNames[fieldName] = {
      ...fieldConfig,
      display_name: displayName
    };
  }
  return fieldsWithDisplayNames;
}

/**
 * 初始化组合查询模块，绑定"添加条件"和"清除条件"按钮事件
 */
async function initComboQuery() {
  // 🔧 确保配置加载完成后再初始化
  await loadComboQueryConfig();
  
  const addBtn = document.getElementById("addConditionBtn");
  if (addBtn) {
    addBtn.addEventListener("click", addConditionRow);
  }
  const clearBtn = document.getElementById("clearConditionsBtn");
  if (clearBtn) {
    clearBtn.addEventListener("click", clearConditions);
  }
  
  console.log("✅ 组合查询模块初始化完成");
}

/**
 * 动态添加一条查询条件行
 * 每行包括：
 *  - 角色选择下拉框（占2列）：选择"统计指标"、"分组"或"筛选"
 *  - 字段下拉框（占3列）：基于 comboQueryConfig 生成所有字段选项
 *  - 运算符下拉框（占2列）：固定选项
 *  - 值输入区域（占3列）：根据字段类型生成对应控件：
 *       * "text": 文本输入框
 *       * "number_range": 生成最小值和最大值输入框
 *       * "multi-select": 生成复选框组（每个选项前添加复选框）
 *       * "checkbox": 生成单个复选框
 *  - 删除按钮（占2列）：删除当前条件行
 */
function addConditionRow() {
  const conditionRow = document.createElement("div");
  conditionRow.className = "condition-row row g-1 mb-1";

  // 角色选择下拉框
  const roleDiv = document.createElement("div");
  roleDiv.className = "col-md-2";
  const roleSelect = document.createElement("select");
  roleSelect.className = "form-select form-select-sm condition-role";
  const defaultRoleOption = document.createElement("option");
  defaultRoleOption.value = "";
  defaultRoleOption.textContent = "选择角色";
  roleSelect.appendChild(defaultRoleOption);
  roleOptions.forEach((item) => {
    const option = document.createElement("option");
    option.value = item.value;
    option.textContent = item.label;
    roleSelect.appendChild(option);
  });
  roleDiv.appendChild(roleSelect);

  // 字段下拉框
  const fieldDiv = document.createElement("div");
  fieldDiv.className = "col-md-3";
  const fieldSelect = document.createElement("select");
  fieldSelect.className = "form-select form-select-sm condition-field";
  const defaultFieldOption = document.createElement("option");
  defaultFieldOption.value = "";
  defaultFieldOption.textContent = "请先选择角色";
  fieldSelect.appendChild(defaultFieldOption);
  fieldSelect.disabled = true;
  fieldDiv.appendChild(fieldSelect);

  // 运算符下拉框
  const operatorDiv = document.createElement("div");
  operatorDiv.className = "col-md-2";
  const operatorSelect = document.createElement("select");
  operatorSelect.className = "form-select form-select-sm condition-operator";
  const operators = [
    { value: "like", label: "like" },
    { value: "=", label: "=" },
    { value: "!=", label: "!=" },
    { value: ">", label: ">" },
    { value: "<", label: "<" },
    { value: ">=", label: ">=" },
    { value: "<=", label: "<=" },
  ];
  operators.forEach((op) => {
    const opOption = document.createElement("option");
    opOption.value = op.value;
    opOption.textContent = op.label;
    operatorSelect.appendChild(opOption);
  });
  operatorDiv.appendChild(operatorSelect);

  // 值输入区域
  const valueDiv = document.createElement("div");
  valueDiv.className = "col-md-3";
  let valueInput = document.createElement("input");
  valueInput.type = "text";
  valueInput.className = "form-control form-control-sm condition-value";
  valueInput.placeholder = "输入查询值";
  valueDiv.appendChild(valueInput);

  // 删除按钮
  const deleteDiv = document.createElement("div");
  deleteDiv.className = "col-md-2";
  const deleteBtn = document.createElement("button");
  deleteBtn.type = "button";
  deleteBtn.className = "btn btn-danger btn-sm condition-delete";
  deleteBtn.textContent = "×";
  deleteBtn.addEventListener("click", function () {
    conditionRow.remove();
    // 🔧 修复：删除条件行后也要更新隐藏输入框
    const conditions = getComboConditions();
    const comboConditionsInput = document.getElementById("comboConditions");
    if (comboConditionsInput) {
      comboConditionsInput.value = JSON.stringify(conditions);
      console.log("🗑️ 删除条件行后，已更新隐藏输入框:", comboConditionsInput.value);
    }
  });
  deleteDiv.appendChild(deleteBtn);

  // 拼接条件行
  conditionRow.appendChild(roleDiv);
  conditionRow.appendChild(fieldDiv);
  conditionRow.appendChild(operatorDiv);
  conditionRow.appendChild(valueDiv);
  conditionRow.appendChild(deleteDiv);

  // 🔧 修复：添加事件监听器，在条件变化时自动更新隐藏输入框
  const updateHiddenInput = () => {
    const conditions = getComboConditions();
    const comboConditionsInput = document.getElementById("comboConditions");
    if (comboConditionsInput) {
      comboConditionsInput.value = JSON.stringify(conditions);
      console.log("🔄 条件变化，已更新隐藏输入框:", comboConditionsInput.value);
    }
  };
  
  // 监听角色、字段、操作符的变化
  roleSelect.addEventListener("change", updateHiddenInput);
  fieldSelect.addEventListener("change", updateHiddenInput);
  operatorSelect.addEventListener("change", updateHiddenInput);
  
  // 监听值输入区域的变化（包括复选框、输入框等）
  valueDiv.addEventListener("change", updateHiddenInput);
  valueDiv.addEventListener("input", updateHiddenInput);
  valueDiv.addEventListener("click", updateHiddenInput);

  // 🔧 根据角色动态过滤字段（配置驱动）
  async function updateFieldOptions(selectedRole) {
    // 清空现有选项（保留默认选项）
    fieldSelect.innerHTML = '<option value="">选择字段</option>';
    // 🔧 使用新的函数获取角色字段配置（包含显示名称）
    const roleFieldsWithDisplayNames = await getRoleFieldsWithDisplayNames(selectedRole);
    // 🔧 配置驱动：直接使用配置表中的字段顺序，确保与后端配置表完全一致
    let roleFields = {};
    let fieldOrder = [];
    if (selectedRole === "metric") {
      roleFields = comboQueryConfig.metric_fields || {};
      fieldOrder = comboQueryConfig.metric_field_order || Object.keys(roleFields);
    } else if (selectedRole === "group") {
      roleFields = comboQueryConfig.group_fields || {};
      fieldOrder = comboQueryConfig.group_field_order || Object.keys(roleFields);
    } else if (selectedRole === "filter") {
      roleFields = comboQueryConfig.filter_fields || {};
      fieldOrder = comboQueryConfig.filter_field_order || Object.keys(roleFields);
    }
    // 按顺序数组渲染
    for (const fieldName of fieldOrder) {
      const fieldConfig = roleFields[fieldName];
      const displayName = roleFieldsWithDisplayNames[fieldName]?.display_name || fieldName;
      const option = document.createElement("option");
      option.value = fieldName;
      option.textContent = displayName;
      fieldSelect.appendChild(option);
    }
  }

  // 角色变化时更新字段选项
  roleSelect.addEventListener("change", async function() {
    const selectedRole = this.value;
    if (!selectedRole) {
      // 未选择角色，禁用字段下拉框并重置
      fieldSelect.innerHTML = '';
      const onlyOption = document.createElement("option");
      onlyOption.value = "";
      onlyOption.textContent = "请先选择角色";
      fieldSelect.appendChild(onlyOption);
      fieldSelect.disabled = true;
      // 友好提示
      alert("请先选择角色，再选择字段！");
      return;
    }
    // 选择了角色，启用字段下拉框
    fieldSelect.disabled = false;
    await updateFieldOptions(selectedRole);
    fieldSelect.value = "";
    valueDiv.innerHTML = "";
    const defaultInput = document.createElement("input");
    defaultInput.type = "text";
    defaultInput.className = "form-control form-control-sm condition-value";
    defaultInput.placeholder = "输入查询值";
    valueDiv.appendChild(defaultInput);
  });

  // 初始状态：未选角色，禁用字段下拉框
  // 只有选择角色后才加载字段选项

  // 根据所选字段更新值输入区域
  fieldSelect.addEventListener("change", async function () {
    const selectedField = fieldSelect.value;
    valueDiv.innerHTML = "";
    
    // === 新增代码：强制干预方式分组的操作符为 "in" ===
    if (selectedField === "intervention_type") {
      const operatorSelect = this.closest(".condition-row").querySelector(
        ".condition-operator"
      );
      operatorSelect.value = "in";
      operatorSelect.disabled = true; // 禁止修改操作符
    }
    // === 新增结束 ===
    
    if (!selectedField) {
      valueInput = document.createElement("input");
      valueInput.type = "text";
      valueInput.className = "form-control form-control-sm condition-value";
      valueInput.placeholder = "输入查询值";
      valueDiv.appendChild(valueInput);
      return;
    }
    
    // 🔧 从角色化配置中查找字段配置
    let config = null;
    if (comboQueryConfig.metric_fields && comboQueryConfig.metric_fields[selectedField]) {
      config = comboQueryConfig.metric_fields[selectedField];
    } else if (comboQueryConfig.group_fields && comboQueryConfig.group_fields[selectedField]) {
      config = comboQueryConfig.group_fields[selectedField];
    } else if (comboQueryConfig.filter_fields && comboQueryConfig.filter_fields[selectedField]) {
      config = comboQueryConfig.filter_fields[selectedField];
    }
    
    if (!config) {
      valueInput = document.createElement("input");
      valueInput.type = "text";
      valueInput.className = "form-control form-control-sm condition-value";
      valueInput.placeholder = "输入查询值";
      valueDiv.appendChild(valueInput);
      return;
    }
    
    // 🔧 使用 control_type 而不是映射为 type
    switch (config.control_type) {
      case "text":
        valueInput = document.createElement("input");
        valueInput.type = "text";
        valueInput.className = "form-control form-control-sm condition-value";
        valueInput.placeholder = "输入查询值";
        valueDiv.appendChild(valueInput);
        break;
      case "number_range":
        const minInput = document.createElement("input");
        minInput.type = "number";
        minInput.className = "form-control form-control-sm condition-value-min";
        minInput.placeholder = "最小值";
        const maxInput = document.createElement("input");
        maxInput.type = "number";
        maxInput.className = "form-control form-control-sm condition-value-max";
        maxInput.placeholder = "最大值";
        const rangeDiv = document.createElement("div");
        rangeDiv.className = "d-flex gap-1";
        rangeDiv.appendChild(minInput);
        rangeDiv.appendChild(maxInput);
        valueDiv.appendChild(rangeDiv);
        break;
      case "multi-select":
        const multiDiv = document.createElement("div");
        multiDiv.className = "d-flex flex-wrap gap-1";
        
        console.log(`🎯 处理 multi-select 字段: ${selectedField}`);
        
        // 🔧 从后端获取字段选项
        const options = await getFieldOptions(selectedField);
        
        console.log(`📋 字段 ${selectedField} 的选项结果:`, options);
        console.log(`📋 选项类型:`, typeof options);
        console.log(`📋 是否为数组:`, Array.isArray(options));
        console.log(`📋 选项长度:`, options ? options.length : 'undefined');
        
        // 🔧 确保options是数组且不为空
        if (options && Array.isArray(options) && options.length > 0) {
          console.log(`✅ 开始创建 ${options.length} 个复选框选项`);
          options.forEach((opt, index) => {
            console.log(`🔘 创建第 ${index + 1} 个选项:`, opt);
            const label = document.createElement("label");
            label.className = "form-check form-check-inline";
            const checkbox = document.createElement("input");
            checkbox.type = "checkbox";
            checkbox.className = "form-check-input condition-value-multi";
            checkbox.value = opt;
            label.appendChild(checkbox);
            const span = document.createElement("span");
            span.className = "form-check-label";
            span.textContent = opt;
            label.appendChild(span);
            multiDiv.appendChild(label);
          });
        } else {
          // 🔧 如果没有选项，显示提示信息
          console.warn(`❌ 字段 ${selectedField} 没有有效选项，显示提示信息`);
          const noOptionsDiv = document.createElement("div");
          noOptionsDiv.className = "text-muted";
          noOptionsDiv.textContent = "该字段暂无选项";
          multiDiv.appendChild(noOptionsDiv);
        }
        
        valueDiv.appendChild(multiDiv);
        break;
      case "checkbox":
        const singleCheckboxDiv = document.createElement("div");
        singleCheckboxDiv.className = "form-check";
        const singleCheckbox = document.createElement("input");
        singleCheckbox.type = "checkbox";
        singleCheckbox.className = "form-check-input condition-value-checkbox";
        singleCheckboxDiv.appendChild(singleCheckbox);
        const checkboxLabel = document.createElement("label");
        checkboxLabel.className = "form-check-label";
        checkboxLabel.textContent = "选中";
        singleCheckboxDiv.appendChild(checkboxLabel);
        valueDiv.appendChild(singleCheckboxDiv);
        break;
      case "number_input":
        valueInput = document.createElement("input");
        valueInput.type = "number";
        valueInput.className = "form-control form-control-sm condition-value";
        valueInput.placeholder = "输入数字";
        valueInput.min = "0";
        valueInput.step = "1";
        valueDiv.appendChild(valueInput);
        break;
      case "date":
        valueInput = document.createElement("input");
        valueInput.type = "date";
        valueInput.className = "form-control form-control-sm condition-value";
        valueInput.placeholder = "选择日期";
        valueDiv.appendChild(valueInput);
        break;
      default:
        valueInput = document.createElement("input");
        valueInput.type = "text";
        valueInput.className = "form-control form-control-sm condition-value";
        valueInput.placeholder = "输入查询值";
        valueDiv.appendChild(valueInput);
        break;
    }
  });

  const container = document.getElementById("advancedQueryContainer");
  if (container) {
    container.appendChild(conditionRow);
  }
}

/**
 * 遍历所有查询条件行，收集条件数据并返回数组
 * 每个条件对象格式：
 * {
 *   role: <角色> ("metric", "group", "filter"),
 *   field: <字段名>,
 *   operator: <运算符>,
 *   value: <查询值>  // "number_range" 为 {min: "", max: ""}；"multi-select" 为数组；"checkbox" 为布尔值
 * }
 */
function getComboConditions() {
  const conditionRows = document.querySelectorAll(".condition-row");
  const conditions = [];
  
  // 🔧 添加调试日志
  console.log("🔍 开始收集查询条件，找到条件行数量:", conditionRows.length);
  
  // 🔧 调试：打印每个条件行的详细信息
  conditionRows.forEach((row, index) => {
    console.log(`📋 条件行 ${index + 1}:`, {
      role: row.querySelector('.condition-role')?.value,
      field: row.querySelector('.condition-field')?.value,
      operator: row.querySelector('.condition-operator')?.value,
      value: row.querySelector('.condition-value')?.value
    });
  });
  
  conditionRows.forEach((row) => {
    const roleEl = row.querySelector(".condition-role");
    const fieldEl = row.querySelector(".condition-field");
    const operatorEl = row.querySelector(".condition-operator");
    let value;
    const role = roleEl ? roleEl.value.trim() : "";
    const field = fieldEl ? fieldEl.value.trim() : "";
    let operator = operatorEl ? operatorEl.value.trim() : "";
    // === 新增代码：强制干预方式分组的操作符为 "in" ===
    if (field === "intervention_type") {
      operator = "in";
    }
    if (!field || !operator) return;
    
    // 🔧 从角色化配置中查找字段配置
    let config = null;
    if (comboQueryConfig.metric_fields && comboQueryConfig.metric_fields[field]) {
      config = comboQueryConfig.metric_fields[field];
    } else if (comboQueryConfig.group_fields && comboQueryConfig.group_fields[field]) {
      config = comboQueryConfig.group_fields[field];
    } else if (comboQueryConfig.filter_fields && comboQueryConfig.filter_fields[field]) {
      config = comboQueryConfig.filter_fields[field];
    }

    // ✅ 精准修复：只检查必要的字段，允许空值
    // 检查角色、字段、操作符是否有效
    if (!role || !field || !operator) {
      return; // 跳过无效行
    }
    /** 
    // === 插入位置开始 ===
    if (BOOLEAN_FIELDS.includes(field)) {
      // 默认使用 `=` 运算符
      value = row.querySelector(".condition-value")
        ? row.querySelector(".condition-value").value.trim()
        : "";
      operator = "="; // 设定运算符为 "="
    }
    // === 插入位置结束 ===
    */

    // 打印调试日志，查看传递的字段、运算符和值
    console.log(`Field: ${field}, Operator: ${operator}, Value: ${value}`);

    if (config) {
      switch (config.control_type) {
        case "number_range":
          const minEl = row.querySelector(".condition-value-min");
          const maxEl = row.querySelector(".condition-value-max");
          value = {
            min: minEl ? minEl.value.trim() : "",
            max: maxEl ? maxEl.value.trim() : "",
          };
          break;
        case "multi-select":
          const checkboxes = row.querySelectorAll(".condition-value-multi");
          value = [];
          checkboxes.forEach((cb) => {
            // 调试输出：打印每个复选框的状态
            console.log(
              "Multi-select - value:",
              cb.value,
              "checked:",
              cb.checked
            );
            if (cb.checked) {
              value.push(cb.value);
            }
          });
          break;
        case "checkbox":
          const checkboxEl = row.querySelector(".condition-value-checkbox");
          value = checkboxEl ? checkboxEl.checked : false;
          break;
        case "number_input":
          const numberEl = row.querySelector(".condition-value");
          value = numberEl ? numberEl.value.trim() : "";
          // 转换为数字类型
          if (value && !isNaN(value)) {
            value = parseInt(value);
          }
          break;
        case "date":
          const dateEl = row.querySelector(".condition-value");
          value = dateEl ? dateEl.value.trim() : "";
          break;
        default:
          const valEl = row.querySelector(".condition-value");
          value = valEl ? valEl.value.trim() : "";
          break;
      }
    } else {
      const valEl = row.querySelector(".condition-value");
      value = valEl ? valEl.value.trim() : "";
    }
    conditions.push({
      role: role,
      field: field,
      operator: operator,
      value: value,
    });
    
    // 🔧 添加调试日志
    console.log("✅ 添加条件:", { role, field, operator, value });
  });

  // 🔧 添加调试日志
  console.log("📊 最终收集到的所有条件:", conditions);
  
  // 🔧 修复：更新隐藏输入框的值，供validateReportParams函数检查
  const comboConditionsInput = document.getElementById("comboConditions");
  if (comboConditionsInput) {
    comboConditionsInput.value = JSON.stringify(conditions);
    console.log("✅ 已更新隐藏输入框 comboConditions:", comboConditionsInput.value);
  }
  
  return conditions;
}

/**
 * 清除所有查询条件行
 */
function clearConditions() {
  const container = document.getElementById("advancedQueryContainer");
  container.innerHTML = "";
}

// 🔧 页面加载时自动初始化
document.addEventListener('DOMContentLoaded', function() {
  initComboQuery();
});

window.getComboConditions = getComboConditions;
window.clearConditions = clearConditions;

// ========================
// 以下代码为从 report.js 中复制过来的 getReportQueryParams() 函数
// 目的是统一构造查询参数，确保报表和图表页面保持一致
// 请确认此处代码在模块中所有依赖变量（如 validParams、comboQueryConfig、getComboConditions）均能正常访问
// ========================

function getReportQueryParams() {
  const params = new URLSearchParams();

  // --- 1. 收集固定查询字段 ---
  // validParams 为预定义的数组，包含 "education_id", "school", "grade", "class_name", "data_year", "name", "gender", "id_card"
  const fixedParams = [
    "education_id",
    "school",
    "grade",
    "class_name",
    "data_year",
    "name",
    "gender",
    "id_card"
  ];
  fixedParams.forEach((param) => {
    const el = document.getElementById(param);
    if (el && el.value.trim()) {
      params.append(param, el.value.trim());
    }
  });

  console.log(params.toString())

  // --- 2. 收集统计时间参数 ---
  const statTimeEl = document.getElementById("statTime");
  if (statTimeEl && statTimeEl.value.trim()) {
    params.append("stat_time", statTimeEl.value.trim());
  }

  console.log(params.toString())

  // --- 3. 收集查询模式参数 ---
  const queryModeEl = document.getElementById("queryMode");
  if (queryModeEl) {
    params.append("query_mode", queryModeEl.value.trim());
  }

console.log(params.toString())

  // --- 4. 根据查询模式处理模板或高级查询条件 ---
  if (queryModeEl.value.trim() === "template") {
    // 模板模式：获取模板下拉框的值
    const templateSelect = document.getElementById("templateSelect");
    if (templateSelect && templateSelect.value) {
      params.append("template", templateSelect.value);
    }
  } else {
    // 自定义查询模式：调用组合查询模块提供的 getComboConditions() 函数获取高级查询条件
    if (typeof getComboConditions === "function") {
      const comboConds = getComboConditions();
      console.log("🔍 getComboConditions() 返回结果:", comboConds);
      if (comboConds && comboConds.length > 0) {
        params.append("advanced_conditions", JSON.stringify(comboConds));
        console.log("✅ 已添加 advanced_conditions:", JSON.stringify(comboConds));
      } else {
        console.warn("⚠️ getComboConditions() 返回空结果或无效结果");
      }
    } else {
      console.error("❌ getComboConditions 函数未定义");
    }
  }

  console.log(params.toString())

  // --- 5. 收集报表名称参数 ---
  const reportNameInput = document.getElementById("reportNameInput");
  if (reportNameInput && reportNameInput.value.trim()) {
    params.append("report_name", reportNameInput.value.trim());
  }

  console.log(params.toString())

  return params;
}
// 将函数挂载到 window 对象，确保全局可访问
window.getReportQueryParams = getReportQueryParams;
// ========================
// 以上为导出的 getReportQueryParams() 函数
// ========================
